<template>
  <div class="app-container">
     <el-form ref="form" :model="form" label-width="80px" :rules="rules"  v-loading="formLoading" >
				<el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="host+'/guard/upload?module=avatar'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.avatar" :src="host+form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
				</el-form-item>
				<el-form-item label="用户名" prop="account" >
					<el-input v-model="form.account"></el-input>
				</el-form-item>
				<el-form-item label="真实姓名" prop="real_name" >
					<el-input v-model="form.real_name"></el-input>
				</el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio v-model="form.gender" label="1">男</el-radio>
          <el-radio v-model="form.gender" label="2">女</el-radio>
        </el-form-item>

				<el-form-item label="电话" prop="phone" >
					<el-input  v-model="form.phone"></el-input>
				</el-form-item>
				<el-form-item label="年龄" prop="age">
					<el-input  type="number" v-model.number="form.age"></el-input>
				</el-form-item>
				<el-form-item label="地址" prop="address" >
					<el-input   v-model="form.address"></el-input>
				</el-form-item>
				<el-form-item label="备注" prop="beizhu">
					<el-input :rows="3" type="textarea" v-model="form.beizhu"></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="2"
            active-text="启用"
            inactive-text="禁用">
          </el-switch>
				</el-form-item>

				<el-form-item v-if="isAdd" >
					<el-button type="primary" @click="onSubmit('form')">立即创建</el-button>
					<el-button  @click="resetForm('form')" >重置</el-button>
				</el-form-item>
				<el-form-item v-else >
					<el-button type="primary" @click="onSubmit('form')">修改</el-button>
				</el-form-item>
			</el-form>
  </div>
</template>

<script>
import { myGet, myPost } from '@/utils/myUtils'

  const urlAddUser = '/guard/user/add';
  const urlDetailUser = '/guard/user/detail';
  export default {
    data() {
      let checkPhone = (rule, value, callback)=>{
            const reg =/^[1][3-9][0-9]{9}$/;
            if(value==''||value==undefined||value==null){
                callback();
            }else {
              if ((!reg.test(value)) && value != '') {
                  callback(new Error('请输入正确的电话号码'));
              } else {
                  callback();
              }
            }
        };
      return {
        isAdd:true,
        formLoading:false,
        host:process.env.VUE_APP_HOST,
        form:{
          id:0,
          account: '',
          real_name: '',
          phone: '',
          age: 20,
          gender: '1',
          beizhu: '',
          avatar: '',
          address: '',
          status:true,
					},
          rules: {
            account: [
                 { required: true, message: '请输入', trigger: 'blur' },
                 { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
            ],
            real_name: [
                { required: true, message: '请输入', trigger: 'blur' },
                { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
            ],
            age: [
                 { required: true, message: '请输入'},
                 { type: 'number', message: '年龄必须为数字值'}
            ],
            phone:[
                { required: true, message: '请输入', trigger: 'blur' },
                { validator: checkPhone, trigger: 'blur' }
            ],
            /* email:[
                { required: true, message: '请输入邮箱格式', trigger: 'blur' },
                { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
            ], */
          },
      }
    },

    methods: {
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
            if (valid) {
              this.formLoading = true;
              myPost(urlAddUser,this.form).then(res=>{
                this.formLoading = false;
                if(res.status){
                  this.$message.success(res.msg);
                  Object.assign(this.$data.form,this.$options.data().form)
                  //如果是编辑操作
                  if(!this.isAdd){
                    this.$router.push({path:'/user/lst'})
                  }
                }
              })
            } else {
                this.$message.error('验证失败！');
                return false;
            }
        });
      },
      handleAvatarSuccess(res, file) {
        if(res.status){
          this.form.avatar = res.data.records.filePath
        }else{
          this.$message.error('上传失败!')
        }
      },
      beforeAvatarUpload(file) {
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
          }
          return isLt2M;
      },
    },
    mounted() {
      const ids = this.$route.params.id;
      if(ids!=undefined){
        myGet(urlDetailUser,{ids}).then(res=>{
          console.log(res)
          if(res.status){
            let user = res.data.records[0]
            user.gender = user.gender+''
            Object.assign(this.form, user)
            this.isAdd = false
          }

        })
      }
    },
  }
</script>

<style>

</style>
